//
//  ViewController.m
//  21-NetWork
//
//  Created by 曹曹 on 16/8/11.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *networkImage;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self postReauest];
}
#pragma mark - NSURLConnection同步
- (IBAction)syncRequest:(id)sender {
    NSURL *imageURL = [NSURL URLWithString:@"http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160808081654350.jpg"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    NSURLResponse *response = nil;
    NSError *error = nil;
    // 使用时间 iOS 2 ~ iOS 9, 已经被弃用
    // 同步请求
    // 参数1: 请求Request
    // 参数2: response指针的地址
    // 参数3: error指针的地址
    NSData *data = [NSURLConnection sendSynchronousRequest:imageURLRequest
                          returningResponse:&response
                                      error:&error];
    if (data) {
        _networkImage.image = [UIImage imageWithData:data];
    } else {
        NSLog(@"%@", error);
    }
}
#pragma mark - NSURLConnection异步
- (IBAction)asyncRequest:(id)sender {
    NSURL *imageURL = [NSURL URLWithString:@"http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160808081654350.jpg"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    [NSURLConnection sendAsynchronousRequest:imageURLRequest
                                       queue:[NSOperationQueue new]
                           completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                               _networkImage.image = [UIImage imageWithData:data];
                           }];
}
#pragma mark - NSURLSession异步
- (IBAction)urlSessionAsync:(id)sender {
    // iOS 7推出
    NSURLSession *urlSession = [NSURLSession sharedSession];/**< 创建单例对象 */
    NSLog(@"%@", urlSession);
    NSURL *imageURL = [NSURL URLWithString:@"http://c.m.163.com/nc/article/headline/T1348647853363/0-20.html?from=toutiao&fn=8&prog=LMA1&passport=E0hiEy3m6T9YgdySTGRBB4BiDAuCFuaDfemrXB2cjSrL2AgtwrES0PPiPHJrLH2UePBK0dNsyevylzp8V9OOiA%3D%3D&devId=lT6C7PXbXgN7vP1MliwCvxnZ2zG4GQCL%2BWhI6AMnlsRkE90xzZzKlH1Sh%2Bl%2Bwi0t&offset=0&size=20&version=14.1&spever=false&net=wifi&lat=1UnpjmV2LRyv3OLxWrph5A%3D%3D&lon=hE7CEQ%2F7j2tR7wCwSyuqRg%3D%3D&ts=1470906775&sign=gjKz%2FtzzfX9V8Q5%2BINDCwb1DpER0IWpJCbDyiVefWsd48ErR02zJ6%2FKXOnxX046I&encryption=1&canal=appstore"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    // URLSession, 网络请求
    // 参数1: request
    // 参数2: Block块(CallBack回调)
    // 注意: Session的回调处于异步线程, 需要返回主线程刷新UI(图片赋值, TableView, CollectionView的刷新等)
    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:imageURLRequest
                  completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                      // 返回主线程执行图片加载
                      //This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
                      dispatch_async(dispatch_get_main_queue(), ^{
                          _networkImage.image = [UIImage imageWithData:data];
                      });
                  }];
    // 让 dataTask执行
    [dataTask resume];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"-----点击-----");
}

- (void)postReauest {
    NSURLSession *urlSession = [NSURLSession sharedSession];
    NSURL *imageURL = [NSURL URLWithString:@"http://open3.bantangapp.com/base/app/init"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"POST";
    imageURLRequest.HTTPBody = [@"app_id=com.jzyd.BanTang&app_installtime=1467276561&app_versions=5.8.5&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&device_token=1aa2741a8e58dbf700d96e588b551a5bf7f8a1e222eb9948c836ba717ce0d48e&os_versions=10.0&screensize=750&track_device_info=iPhone8%2C1&track_deviceid=2BBAE4F7-2E3B-41AA-AE0C-F91FB2BDC279&v=17" dataUsingEncoding:NSUTF8StringEncoding];
    // URLSession, 网络请求
    // 参数1: request
    // 参数2: Block块, CallBack回调
    // 注意: Session的回调中处于异步线程, 需要返回主线程刷新UI(图片赋值, TableView CollectionView的刷新)
    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:imageURLRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 主线程执行图片加载
        dispatch_async(dispatch_get_main_queue(), ^{
            //            _networkImage.image = [UIImage imageWithData:data];
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@", result);
        });
    }];
    // 让 dataTask 执行
    [dataTask resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
